package main

import (
	"crypto/sha1"
	"fmt"
	"io/ioutil"
	"net/http"
	"regexp"
	"strings"
)

const hostsDIR = `C:\Windows\System32\drivers\etc\hosts`
const hostsURL = `https://raw.githubusercontent.com/racaljk/hosts/master/hosts`

func getDate(b []byte) string {
	reg := regexp.MustCompile(`Last updated: ([0-9\-]+)`)
	if reg.Match(b) {
		datab := reg.FindSubmatch(b)[1]
		return string(datab)
	}
	return ""
}

func getGitSha1(b []byte) string {
	tmp := []byte(fmt.Sprintf("blob %d\x00%s", len(b), b))
	return fmt.Sprintf("%x", sha1.Sum(tmp))
}

func main() {
	client := &http.Client{}
	req, _ := http.NewRequest("GET", hostsURL, nil)
	req.Header.Add("If-None-Match", `W/"wyzzy"`)
	resp, _ := client.Do(req)
	if resp.StatusCode == 200 {
		body, _ := ioutil.ReadAll(resp.Body)
		fmt.Println(strings.Trim(resp.Header["Etag"][0], `"`))
		fmt.Println(getGitSha1(body))
		fmt.Println(getDate(body))
		ioutil.WriteFile(hostsDIR, body, 0644)
	}
}
